<style lang="less" xmlns="http://www.w3.org/1999/html">
    @import '../../../styles/common.less';
    @import 'role.less';
</style>

<template>
    <div>
        <Row :gutter="10">
            <Col span="17">
            <Card>
                <p slot="title">
                <Icon type="ios-body" />
                角色列表
            </p>
                <Row>
                    <Input v-model="roleQuery" placeholder="请输入角色名..." style="width: 200px"/>
                    <Input v-model="codeQuery" placeholder="请输入角色编码..." style="width: 200px"/>
                    <Button @click="handleRead" type="primary" icon="search">搜索</Button>
                    <Button @click="handleAdd">添加</Button>
                    <modalForm :show="show" >
                        <div  slot="header" style="color:#f60;text-align:center;margin-bottom: 10px" >
                            <span>添加角色</span>
                        </div>
                        <roleAdd slot="body"></roleAdd>
                    </modalForm>
                </Row>
                <Row class="margin-top-10 searchable-table-con1">
                    <div class="edittable-table-height-con">
                        <can-edit-table highlight-row refs="roles" v-model="records" @on-delete="handleDelete"
                                        @on-change="handleUpdate"
                                        :columns-list="columns"  @on-current-change="onCurrentChange"></can-edit-table>
                    </div>
                </Row>
                <Row class="margin-top-10 searchable-table-con1">
                    <Page :total="totalCount" :page-size="size" show-total @on-change="changePage"></Page>
                </Row>
            </Card>
            </col>
            <Col span="7">
            <Card>
                <Row slot="title">
                    <Button  type="primary" icon="ios-sunny-outline" @click="handleResources">保存资源</Button>
                </Row>

                <Tree ref="resources"  show-checkbox :data="resources" @on-select-change="handleSelectChange" :check-strictly=true :render="renderContent"></Tree>
            </Card>
            </Col>
        </Row>
    </div>
</template>

<script type="text/ecmascript-6">
    import api  from '../../../libs/api'
    import {eventBus}  from '../../../libs/eventBus'
    import roleAdd from './role_add.vue'
    import canEditTable from '../../tables/components/canEditTable.vue';
    import modalForm from "../../my-components/modal-form/modalForm.vue"
    import Tree from "../../my-components/tree/tree.vue"
    export default {
        name: 'role',
        components: {
            canEditTable,
            roleAdd,
            modalForm,
            Tree
        },
        data () {
            return {
                resources:[
                    {
                        title: '资源列表',
                        expand: true,
                        children: []
                    }
                ],
                show:false,
                permissionLevelEnums:[],
                roleId:"",
                records: [],
                current: 1,
                size: 10,
                roleQuery: '',
                codeQuery: '',
                totalCount: 0,
                totalPage: 0,
                columns: [
                    {
                        title: '角色名',
                        key: 'role',
                        editable: true
                    },
                    {
                        title: '角色编码',
                        key: 'code',
                        editable: true
                    },
                    {
                        title: '角色描述',
                        key: 'description',
                        editable: true
                    },
                    {
                        title: '创建时间',
                        key: 'createTime'
                    },
                    {
                        title: '更新时间',
                        key: 'updateTime'
                    },
                    {
                        title: '状态',
                        key: 'status',
                        editable:true,
                        type:"select",
                        option:{data:"statusEnums",key:"name",value:"code"}
                    },
                    {
                        title: '操作',
                        align: 'center',
                        width: 200,
                        key: 'handle',
                        handle: ['edit', 'delete']
                    }
                ]
            }
        },
        mounted(){
            let self=this;
            eventBus.$on("freshenRoleList",function () {
                self.handleRead();
            });
            eventBus.$on("closeModal",function () {
                self.show=false;
            })
        },
        methods: {
            renderContent (h, { root, node, data }) {
                let self=this;
                let element=[];
                //是否读取数据的请求
                if (typeof(data.permission) != "undefined"&&data.permission.indexOf("read")>=0){
                    element=[h('span', [
                        h('span', data.title)
                    ]),
                        h('span', {
                            style: {
                                display: 'inline-block',
                                float: 'right',
                                marginRight: '50px',
                                width:"120px",
                            }
                        }, [
                            h('Select', {
                                    props:{
                                        value: data.permissionLevel,
                                        disabled:!data.checked
                                    },
                                    on: {
                                        'on-change':(value) => {
                                            data.permissionLevel=value;
                                        }
                                    },
                                },self.permissionLevelEnums.map(function(type){
                                    return h('Option', {
                                        props: {value: type.code}
                                    }, type.name);
                                })
                            )
                        ])];
                }else{
                    element=[h('span', [
                        h('span', data.title)
                    ])];
                }
                return h('span', {
                    style: {
                        display: 'inline-block',
                        width: '100%'
                    }
                },element);

            },
            //清空选择的资源
            handleClearAll(){
                this.$set(this.resources[0], 'checked',false);  //需要清除根部属性否则无法全部清空
                this.$set(this.resources[0], 'indeterminate',false);  //需要清除根部属性否则无法全部清空
                this.handleAllResources(this.resources[0].children,false);
            },
            //加载角色列表
            handleRead(){
                this.handleClearAll();
                let data = {};
                data.roleQuery = this.roleQuery;
                data.codeQuery = this.codeQuery;
                data.current = this.current;
                data.size = this.size;
                this.$get(api.roles.base, data).then(response => {
                    this.totalPage = this.util.calTotalPage(response.obj.total, this.size);
                    this.totalCount = response.obj.total;
                    this.records = [];
                    for (let i in response.obj.records) {
                        this.records.push(response.obj.records[i])
                    }
                });
            },
            //加载资源树
            loadResource(){
                let self=this;
                let data = {};
                this.$get(api.resources.tree, data).then(response => {
                    let resourcesRecords=[];
                    response.obj.forEach(function (resource) {
                        //树形tree所需数据格式
                        resource.title=resource.name;
                        resource.expand=false;
                        self.loadTree(resource);
                        resourcesRecords.push(resource);
                        self.permissionLevelEnums=resource.permissionLevelEnums;
                    });
                    self.$set(self.resources[0], 'children', resourcesRecords);
                });
            },
            loadTree(resource){
                var self=this;
                var childrenArray=[];
                resource.childrensView&&resource.childrensView.forEach(function (childrens) {
                    var children={};
                    children=childrens;
                    //树形tree所需数据格式
                    children.title=childrens.name;
                    children.expand=false;
                    childrenArray.push(children);
                });
                resource.children=childrenArray;
                childrenArray.forEach(function (item) {
                    if(item.childrensView&&item.childrensView.length>0)
                        self.loadTree(item);
                    else
                        item.children=[];
                })
            },
            //删除角色
            handleDelete (val, index) {
                this.$delete(api.roles.base+"/"+val.id,null);
            },
            //更新角色
            handleUpdate (val, index) {
                delete val[index]["statusEnums"]; //删除枚举数据
                this.$put(api.roles.base+"/"+val[index].id,val[index]).then(response=>{
                    this.handleRead();
                })
            },
            changePage(index){
                this.current = index;
                let data = {};
                this.search(data);
            },
            //添加角色
            handleAdd: function() {
                this.show=true;
            },
            handleSelectChange(data){
                data.expand=!data.expand;

            },
            onCurrentChange(data,index){
                let self=this;
                self.roleId=data.id;
                self.$get(api.roles.resources.replace("{id}",data.id),{}).then(response => {
                    let all=false;
                    response.obj.forEach(function (resource) {
                        if(resource.permission=="*:*"){ //全部资源
                            all=true;
                        }
                    });
                    if(all){
                        self.handleAllResources(self.resources[0].children,true);
                    }else{
                        self.$set(self.resources[0], 'checked',false);  //需要清除根部属性否则无法全部清空
                        self.$set(self.resources[0], 'indeterminate',false);  //需要清除根部属性否则无法全部清空
                        self.handleAllResources(self.resources[0].children,false);
                        response.obj.forEach(function (match) {//匹配权限
                            self.matchResource(self.resources[0].children,match);
                        });
                    }
                });
            },
            handleResources(){
                let data={}
                data.roleResources=this.$refs.resources.getCheckedNodes();
                this.$post(api.roles.resources.replace("{id}",this.roleId),data);
            },
            handleExpand(parent,resources,match){
                let self=this;
                resources.forEach(function (resource) {
                    if(resource.id==match.id){
                        self.$set(parent, 'expand',true);
                        self.handleExpand(self.resources[0],self.resources[0].children,parent);
                    }
                    if(resource.children.length>0)
                       self.handleExpand(resource,resource.children,match);
                })
            },
            //匹配权限
            matchResource(resources,match){
                let self=this;
                 resources.forEach(function (resource) {
                    if(resource.id==match.id){
                        self.$set(resource, 'checked',true);
                        self.$set(resource, 'expand',true);
                        //展开父节点
                        self.handleExpand(self.resources[0],self.resources[0].children,match)
                        resource.permissionLevel=match.permissionLevel;  //角色资源数据字段权限
                    }
                    if(resource.children.length>0){
                        self.matchResource(resource.children,match);
                    }
                })
            },

            //清空或者选择所有资源
            handleAllResources (resources,checked){
                let self=this;
                resources.forEach(function (resource) {
                    self.$set(resource, 'checked',checked);
                    self.$set(resource, 'indeterminate',checked);
                    self.$set(resource, 'expand',false);
                    if(resource.children.length>0)
                        self.handleAllResources(resource.children,checked);
                })
            },
        },
        created(){
            this.handleRead();
            this.loadResource();
        }
    }
</script>

<style>

</style>
